#include "projektdock.h"

ProjectDock::ProjectDock(QWidget *parent) : QDockWidget(parent)
{
    this->_rootDir = 0;
    this->_currentSelectedDir = 0;

    this->setWindowTitle(tr("Project Viewer"));
    this->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    this->setWidget(&this->_treeView);

    this->initTreeView();
}

void ProjectDock::setModel(ProjectModel *model)
{
    this->_rootDir = model->projectData();
    this->_model = model;
    this->_treeView.setModel(this->_model);

    emit this->drawPackage(this->_rootDir);
}

void ProjectDock::initTreeView()
{
    this->_treeView.setHeaderHidden(true);
    this->_treeView.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->_treeView.setAlternatingRowColors(true);
    //this->_treeView.setModel(this->_model);

    QObject::connect(&this->_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(itemSelected(QModelIndex)));
}

void ProjectDock::itemSelected(QModelIndex index)
{
    UmlGraphicsItem *selectedItem = static_cast<UmlGraphicsItem*>(index.internalPointer());
    UmlDirItem *dir;

    if (selectedItem->isOfType(UmlItem::UmlPackageItemType)) {
        dir = static_cast<UmlDirItem*>(selectedItem);
    }

    else if (selectedItem->isOfType(UmlItem::UmlClassItemType)){
        UmlClassItem *cl = static_cast<UmlClassItem*>(selectedItem);

        dir = cl->parentDir() == 0 ? this->_rootDir : cl->parentDir();
    }

    if (dir != this->_currentSelectedDir) {
        this->_currentSelectedDir = dir;
        emit this->drawPackage(dir);
    }
}
